﻿using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

namespace nMongo
{
    public partial class MongoRepository<T>
    {
        public virtual bool DeleteById(object id)
        {
            WriteConcernResult result;
            return DeleteById(id, out result);
        }

        public virtual bool DeleteById(object id, out WriteConcernResult result)
        {
            return DeleteById(id, WriteConcern.Acknowledged, out result);
        }

        public virtual bool DeleteById(object id, WriteConcern concern, out WriteConcernResult result, T deletedObject = null)
        {
            if (deletedObject == null)
                deletedObject = GetById(id);

            result = OriginalCollection.Remove(Query.EQ("_id", BsonValue.Create(id)), concern);
            bool returned = (result != null && result.Ok || result.DocumentsAffected > 0);

            if (returned)
            {
                this.AutoDetectPersistencyById(MongoPersistencyState.Removed, id);                
                this.AutoDetectGraveyardAdd(deletedObject);
            }
            return returned;
        }
    }
}
